﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Cloudthentic.SSIS.Server
{
    /// <summary>
    /// SSIS Executor Service
    /// </summary>
    public class Executor : Cloudthentic.SSIS.Server.IExecutor
    {


        public Configuration.SsisServerConfiguration SsisServerConfiguration  { get; set; }

        public void Execute(
            string packageName, 
            System.Collections.Generic.List<SsisVariable> variables)
        {


            Microsoft.SqlServer.Dts.Runtime.IDTSEvents events = null;
            Microsoft.SqlServer.Dts.Runtime.Package pkg = SsisApplication.Application.LoadPackage(this.ResolvePackagePath(packageName), events);
            this.AssignVariables(pkg, variables);

            pkg.Execute();

        }

        protected string ResolvePackagePath(string packageName)
        {
            string path = string.Format(@"{0}\{1}", this.SsisServerConfiguration.PackageDeploymentFolder.TrimEnd('\\'), this.SsisServerConfiguration.SsisPackages[packageName].PackagePath.TrimStart('\\'));
            return path;
        }

        protected void AssignVariables(Microsoft.SqlServer.Dts.Runtime.Package pkg, System.Collections.Generic.List<SsisVariable> variables)
        {

            if (pkg == null) throw new NullReferenceException("Executor::AssignVariables - pkg has a null reference");

            if (variables != null)
            {
                foreach (SsisVariable variable in variables)
                {
                    if (pkg.Variables.Contains(variable.Name)) pkg.Variables[variable.Name].Value = variable.Value; // todo: potential type missmatch
                }
            }
        }
    }
}
